package com.qfedu.ssm.utils;
import com.qfedu.ssm.dao.PermissionDAO;
import com.qfedu.ssm.dao.RoleDAO;
import com.qfedu.ssm.dao.UserDAO;
import com.qfedu.ssm.pojos.User;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class MyRealm extends AuthorizingRealm {


    private UserDAO userDAO;

    public void setUserDAO(UserDAO userDAO) {
        this.userDAO = userDAO;
    }
    @Autowired
    private RoleDAO roleDAO;
    @Autowired
    private PermissionDAO permissionDAO;


    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        //获取授权用户信息principalCollection存放了认证成功的用户信息
        User user = (User) principalCollection.iterator().next();
        int userId = user.getId();

        //2.通过user的id查询当前用户的所有角色名 ---Set<String>


        //3.通过user的id查询当前用户的所有权限percode ---Set<String>

       SimpleAuthorizationInfo authorizationInfo =  new SimpleAuthorizationInfo();
        authorizationInfo.setRoles(roleDAO.queryRolesByUserId(userId));
        authorizationInfo.setStringPermissions(permissionDAO.queryPermissionByUserId(userId));
        return authorizationInfo;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        //1.从token中获取用户名
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String username = token.getUsername();
        String password = new String(token.getPassword());

        //2.根据用户名查询数据库(UserDAO),得到一个User对象
        User user = userDAO.queryUserByName(username);
        if (user==null){
            throw new UnknownAccountException("账号不存在！");
        }else {
            //用户验证密码
            String md5Pwd = new SimpleHash("MD5",password).toHex();
            if (!user.getUserPwd().equals(md5Pwd)){
                throw new IncorrectCredentialsException("密码不正确！");
            }
        }


        return new SimpleAuthenticationInfo(user,password,getName());
    }
}
